import { useCallback, useEffect } from 'react';
import { cleanObject } from './index';
import { useHttp } from './http';
import { useAsync } from './use-async';
import { Project } from 'screens/project-list/list';

/**
 * 查询项目
 * @param param
 */
export const useProjects = (param?: Partial<Project>) => {
  const client = useHttp();
  const { run, ...result } = useAsync<Project[]>();
  const fetchProjects = useCallback(() => client('projects', { data: cleanObject(param || {}) }), [param, client]);

  useEffect(() => {
    run(fetchProjects(), {
      retry: fetchProjects,
    });
  }, [param, run, fetchProjects]);
  return result;
};

/**
 * 修改项目
 */
export const useEditProject = () => {
  const client = useHttp();
  const { run, ...asyncResult } = useAsync();
  const mutate = (params: Partial<Project>) => {
    return run(
      client(`projects/${params.id}`, {
        method: 'PATCH',
        data: params,
      })
    );
  };
  return {
    mutate,
    ...asyncResult,
  };
};

export const useAddProject = () => {
  const client = useHttp();
  const { run, ...asyncResult } = useAsync();
  const mutate = (params: Partial<Project>) => {
    return run(
      client(`projects/${params.id}`, {
        method: 'POST',
        data: params,
      })
    );
  };
  return {
    mutate,
    ...asyncResult,
  };
};
